import moment from "moment";
import { message } from "antd";

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : "0" + n;
};

// 深拷贝
export function deepClone (obj){
  if(obj === null || typeof obj !== 'object'){
    return obj
  }
  let _obj = Array.isArray(obj) ? [] : {} //数组兼容
  for (let k in obj) {
    if (obj.hasOwnProperty(k)) {
      if (typeof obj[k] === 'object') {
        _obj[k] = deepClone(obj[k]);
      } else {
        _obj[k] = obj[k];
      }
    }
  }
  return _obj
}

// 获取cookies
export function getCookie(name, cookieStr) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"),
    cookie = cookieStr || document.cookie;
  if ((arr = cookie.match(reg))) {
    return unescape(arr[2]);
  } else {
    return null;
  }
}

// 从current日期开始，到接下来一周的日期
export function getOneWeekDate(start_date) {
  let startDate = start_date || new Date();
  let dateArr = [];
  for (let i = 0; i < 7; i++) {
    let newDate = new Date(startDate.getTime() + i * 1000 * 60 * 60 * 24);
    let year = newDate.getFullYear();
    let month =
      parseInt(newDate.getMonth()) + 1 > 9
        ? parseInt(newDate.getMonth()) + 1
        : "0" + (parseInt(newDate.getMonth()) + 1);
    let day =
      newDate.getDate() > 9 ? newDate.getDate() : "0" + newDate.getDate();
    let fullDate = `${year}-${month}-${day}`,
      fullWeek = moment(fullDate).format("dddd");
    dateArr.push({
      date: fullDate,
      week: fullWeek,
    });
  }
  return dateArr;
}

// 日期当天，格式如：2020-10-10
// _day：代表当天日期，往后推day天
export function formatDate(date, _day) {
  if (_day > 0) {
    date.setDate(date.getDate() + _day);
  }
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return [year, month, day].map(formatNumber).join("-");
}

// 根据相差日期，计算天数
export function totalDays (start, end){
  const startTime = new Date(start).getTime(),
        endTime = new Date(end).getTime();
  const total = endTime - startTime;
  const days = Number.parseInt(total/(1000*60*60*24));
  return days
}

// 格式化日期
export function formatTimeString(str) {
  if(str){
      str = str.replace(/-/g, '.');
      return str.slice(0, 10)
  }
  return str
}

// 替换url
export function replaceImageUrl(url) {
  if (url) {
    return url.replace("http://tx.enn.cn", "https://tx.enn.cn");
  }
  return "";
}

// 替换 \n 到 <br>
export function replaceContent(txt) {
  if (txt) {
    return txt.replace(/\n|\\n/g, "<br/>");
  }
  return "";
}

// xss 攻击反转义
export function HTMLDecode(str) {
  let temp = "";
  if (str.length == 0) return "";
  temp = str.replace(/&amp;/g, "&");
  temp = temp.replace(/&lt;/g, "<");
  temp = temp.replace(/&gt;/g, ">");
  temp = temp.replace(/&nbsp;/g, " ");
  temp = temp.replace(/&#39;/g, "'");
  temp = temp.replace(/&quot;/g, '"');
  temp = temp.replace(/\n/g, "\\\\n");
  temp = temp.replace(/[\n\r\n]/g, "\\r\\n");
  return temp;
}

// 判断url跳转
export function targetUrl(item) {
  let { projectId, categoryId, goodsId, id } = item;
  if (projectId == 1) {
    return `/ticket/${goodsId || id}.html`;
  } else if (projectId == 2) {
    if (categoryId == 1) {
      // 车辆
      return `/car/${goodsId || id}.html`;
    } else if (categoryId == 2) {
      // 线路
      return `/line/${goodsId || id}.html`;
    }
  } else if (projectId == 3) {
    return `/hotel/${goodsId || id}.html`;
  }
  return "/";
}

// 验证每位乘客身份证信息，是否满足特定购票要求
// 判断用户年龄/性别是否符合购票要求
export function loopEvetyIdCard(realName, idCardArr, _requires, _goodsName) {
  let requires = sessionStorage.getItem("requires") || _requires;
  // realname: 1 无需实名  2 一位实名  3 多位实名
  // requires 不存在时， 无要求
  if (realName == 1 || requires === "null" || !requires) {
    return true;
  }
  if (requires && requires.indexOf("{") >= 0) {
    requires = JSON.parse(requires) || {};
    return idCardArr.every((item) =>
      validateInfoByIDCard(item.idCard, requires, _goodsName)
    );
  }
  return true;
}
// 判断用户身份证信息（年龄/性别）是否符合购票要求
function validateInfoByIDCard(idCard, requires, _goodsName = "") {
  // identity: 0 无要求  1 要求
  // sex: 0 无  1 男  2 女
  const { age = "", identity, sex } = requires,
    ageScale = age.split("-") || [],
    result = getIDCardInfo(idCard);
  // 无需验证身份
  if (identity == 0) {
    return true;
  } else if (identity > 0) {
    // 需要身份验证
    // 年龄在 age 范围内
    if (result.age >= ageScale[0] && result.age <= ageScale[1]) {
      if (sex == 0 || sex == result.sex) {
        return true;
      } else if (sex == 1 || sex == 2) {
        if (result.sex != sex) {
          message.warning(`${_goodsName}票型只限${sex == 1 ? "男" : "女"}性游客使用，请重新填写`);
          return false;
        }
      }
      return true;
    } else {
      message.warning(`${_goodsName}游客年龄超出${age}岁范围，不符合购票要求，请重新填写`);
      return false;
    }
  }
  return true;
}
//根据身份证获取用户年纪和性别
function getIDCardInfo(identityCard) {
  let travelerInfo = {};
  var len = (identityCard + "").length;
  if (len == 0) {
    return 0;
  } else {
    if (len != 15 && len != 18) {
      //身份证号码只能为15位或18位其它不合法
      return 0;
    }
  }
  var strBirthday = "";
  if (len == 18) {
    //处理18位的身份证号码从号码中得到生日和性别代码
    strBirthday =
      identityCard.substr(6, 4) +
      "/" +
      identityCard.substr(10, 2) +
      "/" +
      identityCard.substr(12, 2);
  }
  if (len == 15) {
    strBirthday =
      "19" +
      identityCard.substr(6, 2) +
      "/" +
      identityCard.substr(8, 2) +
      "/" +
      identityCard.substr(10, 2);
  } //时间字符串里，必须是“/”
  var birthDate = new Date(strBirthday);
  var nowDateTime = new Date();
  var age = nowDateTime.getFullYear() - birthDate.getFullYear(); //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (
    nowDateTime.getMonth() < birthDate.getMonth() ||
    (nowDateTime.getMonth() == birthDate.getMonth() &&
      nowDateTime.getDate() < birthDate.getDate())
  ) {
    age--;
  }
  travelerInfo.age = age;
  travelerInfo.sex = (identityCard.substr(16, 1) * 1) % 2 == 0 ? 2 : 1;
  return travelerInfo;
}

// 验证身份证号
export function validateIDCard(id) {
  // 1 "验证通过!", 0 //校验不通过 // id为身份证号码
  var reg =
    /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
  //号码规则校验
  if (!reg.test(id)) {
    return { status: 0, msg: "身份证号码不合规" };
  }
  //区位码校验
  //出生年月日校验  前正则限制起始年份为1900;
  var year = id.substr(6, 4), //身份证年
    month = id.substr(10, 2), //身份证月
    date = id.substr(12, 2), //身份证日
    time = Date.parse(month + "-" + date + "-" + year), //身份证日期时间戳date
    now_time = Date.parse(new Date()), //当前时间戳
    dates = new Date(year, month, 0).getDate(); //身份证当月天数
  if (time > now_time || date > dates) {
    return { status: 0, msg: "出生日期不合规" };
  }
  //校验码判断
  var c = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //系数
  var b = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"); //校验码对照表
  var id_array = id.split("");
  var sum = 0;
  for (var k = 0; k < 17; k++) {
    sum += parseInt(id_array[k]) * parseInt(c[k]);
  }
  if (id_array[17].toUpperCase() != b[sum % 11].toUpperCase()) {
    return { status: 0, msg: "身份证校验码不合规" };
  }
  return { status: 1, msg: "校验通过" };
}

// 验证手机号
export function validatePhoneNo(str) {
  let reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
  return reg.test(str);
}

// 处理url中的query，空值过滤掉
export function queryCheckEmpty(query) {
  if(Object.prototype.toString.call(query) == '[object Object]'){
    Object.keys(query).forEach(q => {
      if(!query[q]){
        delete query[q]
      }
    });
    return query
  }
  return query
}

// 处理url中的id
export function getID(str) {
  if(str.includes('.')){
    return str.split('.')[0]
  }
  return str
}

// 处理小数
export function formatNumTo2(num) {
  let _num = +num;
  return Number.isInteger(_num) ? _num : _num?.toFixed(2)
}

// 优惠类型
export function formatActicityType (type){
  switch(type){
    case 1: return '早定优惠';
    case 2: return '特价直减';
    case 3: return '满减优惠';
  }
}

// 优惠券类型
export function formatActivityClass (type){
  if(!type){
    return "";
  }
  switch(type){
    case 1: return 'youhui-zd';
    case 2: return 'youhui-tj';
    case 3: return 'youhui-mj';
    default: return 'youhui-yhq';
  }
}